﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Iris.Engine;
using System.IO;
using ModEngine;


namespace Iris.UI
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Duel2Window window;

        public MainWindow()
        {
            InitializeComponent();
        }

        List<Vignette> vignettes = new List<Vignette>();

        private void on_LoadDataSourceEvent(ImageSort imageSort)
        {

            grid.Dispatcher.Invoke(new Action(delegate()
            {
                bool added = false;
                for(int i = 0; i < grid.Children.Count; i++){
                    Vignette ImageUI = grid.Children[i] as Vignette;
                    if (ImageUI != null)
                    {
                        if (ImageUI.Image.Score < imageSort.Score) {
                            Vignette v= Vignette.Create(imageSort);
                            grid.Children.Insert(i,v);
                            lock (vignettes) { vignettes.Add(v); }
                            added = true;
                            break;
                        }
                    }
                }
                if (!added)
                {
                    Vignette v = Vignette.Create(imageSort);
                    grid.Children.Add(v);
                    lock (vignettes) { vignettes.Add(v); }
                }
                
            }), DispatcherPriority.Render);
        }

        private void on_BeginLoadDataSourceEvent(string path)
        {
            Dispatcher.Invoke(new Action(delegate()
            {
                grid.Children.Clear();
                lock (vignettes) { vignettes.Clear(); }
                new NotificationWindow(path).Show();
                progessBar.Visibility = System.Windows.Visibility.Visible;
                progessBar.Value = 0;
            }), DispatcherPriority.Render);
        }

        private void on_EndLoadDataSourceEvent() {

            Dispatcher.Invoke(new Action(delegate()
            {
                new NotificationWindow("Fin du chargement").Show();
                log.Content = "Fin du chargement";
                progessBar.Visibility = System.Windows.Visibility.Collapsed;
            }), DispatcherPriority.Render);
        }

        private void on_WaitLoadDataSourceEvent(ImageSort image, int index, int total) {

            Dispatcher.Invoke(new Action(delegate() {
                    log.Content = String.Format("Chargement en cours .../{0}/{1}", image.DataSource.Directory.Name, image.DataSource.Name );
                    progessBar.Value = (index*100 / total);
            }), DispatcherPriority.Render);
        }

        private void on_EndLoadModuleEvent()
        {

            menu1.Dispatcher.Invoke(DispatcherPriority.Render,
            new Action(delegate()
            {
                menu1.IsEnabled = true;
            }));
        }

        private void on_LoadModuleEvent(IModule module)
        {
            listBoxModules.Dispatcher.Invoke(DispatcherPriority.Render,
            new Action(delegate()
            {
                listBoxModules.Items.Add(String.Format("{0} - version {1}", module.getNameModule(), module.getVersion()));
            }));
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SortCore.singleton.BeginLoadDataSourceEvent += on_BeginLoadDataSourceEvent;
            SortCore.singleton.WaitLoadDataSourceEvent += on_WaitLoadDataSourceEvent;
            SortCore.singleton.LoadDataSourceEvent += on_LoadDataSourceEvent;
            SortCore.singleton.LoadDataSourceFailedEvent  += on_LoadDataSourceFailedEvent;
            SortCore.singleton.EndLoadDataSourceEvent += on_EndLoadDataSourceEvent;

            SortCore.singleton.ImagesUpdatedEvent += OnImagesUpdated;
            SortCore.singleton.LoadModuleEvent += on_LoadModuleEvent;
            SortCore.singleton.EndLoadModuleEvent += on_EndLoadModuleEvent;
            SortCore.singleton.BeginLoadModule(@".\");
        }

        private void OnImagesUpdated(List<ImageSort> images)
        {
            grid.Dispatcher.Invoke(new Action(delegate()
            {
                grid.BeginInit();
                grid.Children.Clear();
                lock (vignettes)
                {
                    vignettes = vignettes.OrderByDescending(b => b.Image.Rating).ToList();

                    foreach (Vignette v in vignettes)
                    {
                        grid.Children.Add(v);
                        v.Update();
                    }
                }
                grid.EndInit();

            }), DispatcherPriority.Render);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            SortCore.singleton.Dispose();
        }

        private void OnChoisirDossier(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            
            System.Windows.Forms.DialogResult result =  dialog.ShowDialog();

            if (dialog.SelectedPath != String.Empty && result == System.Windows.Forms.DialogResult.OK)
            {
                SplashPanel.Visibility = System.Windows.Visibility.Collapsed;
                SortCore.singleton.BeginLoadDataSource(dialog.SelectedPath);
            }
        }
        
        private void on_LoadDataSourceFailedEvent(FileInfo file) {
            log.Dispatcher.Invoke( new Action(delegate (){
            new NotificationWindow("Erreur sur " + file.Name).Show();
            }), DispatcherPriority.Send);
        }

        private void on_DuelWindowClosed(object sender, EventArgs e)
        {
            window = null;
            this.Activate();
        }

        private void OnDemanderDuel(object sender, RoutedEventArgs e)
        {
            if (window == null) {
                window = new Duel2Window();
                window.Closed += on_DuelWindowClosed;
            }
            try
            {
                window.Show();
                window.Focus();
            }
            catch (Exception) { }
            
        }

        private void OnSauverFiveStars(object sender, RoutedEventArgs e)
        {
            var a = from v in vignettes select v.Image;

            JobWindow job = JobWindow.Create(a.ToList());
            job.ShowDialog();
        }
    }
}
